import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { showNotify, closeToast } from "vant";
import router from "@/router";

// API响应结构
export interface ApiResponse<T = any> {
	code: number;
	data: T;
	message: string;
}

// 创建axios实例
const service = axios.create({
	baseURL: import.meta.env.VITE_API_BASE_URL || "http://localhost:3000",
	timeout: 5000,
});

// 请求拦截器
service.interceptors.request.use(
	(config) => {
		const token = localStorage.getItem("token");
		if (token) {
			config.headers.Authorization = `Bearer ${token}`;
		}
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

// 响应拦截器
service.interceptors.response.use(
	(response: AxiosResponse): AxiosResponse | Promise<AxiosResponse> => {
		const res = response.data as ApiResponse;
		console.log(res);
		if (res.code !== 200) {
			showNotify({
				type: "danger",
				message: res.message || "请求失败",
			});

			// token过期或无效
			if (res.code === 401) {
				localStorage.removeItem("token");
				router.replace("/login");
			}

			return Promise.reject(response);
		}

		response.data = res;
		return response.data;
	},
	(error) => {
		closeToast();
		console.error("响应错误：", error);

		// 处理网络错误
		let message = "网络错误，请稍后重试";
		if (error.response) {
			const status = error.response.status;

			// 根据状态码定制错误信息
			switch (status) {
				case 400:
					message = "请求参数错误";
					break;
				case 401:
					message = "请先登录";
					// 清除token
					localStorage.removeItem("token");
					// 跳转到登录页
					router.replace("/login");
					break;
				case 403:
					message = "没有访问权限";
					break;
				case 404:
					message = "请求资源不存在";
					break;
				case 500:
					message = "服务器内部错误";
					break;
				default:
					message = `网络错误(${status})`;
			}
		} else if (error.message.includes("timeout")) {
			message = "请求超时，请稍后重试";
		}

		showNotify({
			type: "danger",
			message,
		});

		return Promise.reject(error?.response?.data);
	}
);

// 封装GET请求
function get<T = any>(
	url: string,
	params?: any,
	config?: AxiosRequestConfig
): Promise<ApiResponse<T>> {
	return service.get(url, { params, ...config }) as unknown as Promise<
		ApiResponse<T>
	>;
}

// 封装POST请求
function post<T = any>(
	url: string,
	data?: any,
	config?: AxiosRequestConfig
): Promise<ApiResponse<T>> {
	return service.post(url, data, config) as unknown as Promise<ApiResponse<T>>;
}

// 封装PUT请求
function put<T = any>(
	url: string,
	data?: any,
	config?: AxiosRequestConfig
): Promise<ApiResponse<T>> {
	return service.put(url, data, config) as unknown as Promise<ApiResponse<T>>;
}

// 封装PATCH请求
function patch<T = any>(
	url: string,
	data?: any,
	config?: AxiosRequestConfig
): Promise<ApiResponse<T>> {
	return service.patch(url, data, config) as unknown as Promise<ApiResponse<T>>;
}

// 封装DELETE请求
function del<T = any>(
	url: string,
	config?: AxiosRequestConfig
): Promise<ApiResponse<T>> {
	return service.delete(url, config) as unknown as Promise<ApiResponse<T>>;
}

export default {
	get,
	post,
	put,
	patch,
	delete: del,
};
